<template>
    <Form
        ref="form"
        :label-width="120"
        :show-message="false"
        :rules="rules"
        :model="form">
            <h2 class="margin-bottom-20 border-bottom" style="padding-bottom:20px">长时间未开门配置</h2>
            <FormItem label="配置模式:" prop="model" v-if="modelType">
                <Select v-model="form.model" style="width: 280px">
                    <Option v-for="option in modelOptions" :key="option.label" :value="option.value">
                        {{option.label}}
                    </Option>
                </Select>
                <span style="margin-left:30px;color:#888">如无独立配置需求，请选择统一配置</span>
            </FormItem>
            <FormItem label="开启预警:"  prop="enable_alarm">
                <i-switch v-model="form.enable_alarm" :disabled="isDisabled"></i-switch>
            </FormItem>
            <FormItem label="预警时长:"  prop="alarm_time">
                <Select v-model="form.alarm_time" style="width: 280px" :disabled="isDisabled">
                    <Option v-for="option in options" :key="option" :value="option">
                        {{option}}小时
                    </Option>
                </Select>
            </FormItem>
            <FormItem label="普通密码:"  prop="forbid_add_password" v-if="isShowLock">
                <!-- <Select v-model="form.forbid_add_password" style="width: 280px">
                    <Option v-for="(option, index) in addPasswordTypes" :key="index" :value="option.value">
                        {{option.name}}
                    </Option>
                </Select> -->
                <i-switch v-model="form.forbid_add_password" :disabled="isDisabled"></i-switch>
                <span style="margin-left: 10px">{{`租客入住后，${form && form.forbid_add_password ? '禁止' : '可'}新增时效密码`}}</span>
            </FormItem>
            <FormItem label="临时密码:"  prop="forbid_add_tmp_password" v-if="isShowLock">
                <i-switch v-model="form.forbid_add_tmp_password" :disabled="isDisabled"></i-switch>
                <span style="margin-left: 10px">{{`租客入住后，${form && form.forbid_add_tmp_password ? '禁止' : '可'}新增临时密码`}}</span>
            </FormItem>
            <FormItem label="超时未锁提醒:" prop="alarm_unlock">
                <span style="display:inline-block;width: 280px">10分钟</span>
                <span style="margin-left:30px;color:#888">限指定型号门锁支持</span>
            </FormItem>
            <FormItem label="短信推送:" prop="msg_notify" v-if="showUser">
                <Tag
                    v-for="(phone, index) in form.msg_notify"
                    :key="phone"
                    type="dot"
                    closable
                    @on-close="handleDelNotify(index)"
                >
                    {{phone}}
                </Tag>
                <span v-show="form.msg_notify.length === 0">暂无推送对象</span>
                <Poptip v-model="visible" title="输入手机号码">
                    <i-button @click="visible = true">添加</i-button>
                    <div slot="content" class="poptip-content">
                        <i-input style="width:120px" size="small" placeholder="新增手机号码" v-model.trim="newPhone" />
                        <i-button size="small" @click="handleAddNotify" >确认</i-button>
                        <i-button size="small" @click="visible = false" >取消</i-button>
                        <div class="margin-top-10" v-show="phoneError">{{phoneError}}</div>
                    </div>
                </Poptip>
                <i-button class="margin-left-10" type="primary" :loading="submiting" @click="$emit('onNotifySave')">保存</i-button>
                <div style="color:#888">超过10分钟未恢复通知对应管理人员</div>
            </FormItem>
            <!-- <h2 class="margin-bottom-20 border-bottom" style="padding-bottom:20px">低电提醒配置</h2>
            <FormItem label="低电提醒:" prop="low_power">
                <Select v-model="form.low_power" style="width: 280px" :disabled="isDisabled">
                    <Option v-for="option in lowPowerOptions" :key="option" :value="option">
                        {{option}}%
                    </Option>
                </Select>
            </FormItem> -->
    </Form>
</template>

<script>
    import debounce from 'lodash/debounce'
import pick from 'lodash/pick'
import isEqual from 'lodash/isEqual'
import { http, api } from '@/libs/http'

export default {
      name: 'lock-setting',
      props: {
        value: Object,
        showUser: Boolean,
        submiting: Boolean,
        defaultConfig: Object, // 默认配置
        isShowLock: {
          type: Boolean,
          default: false
        },
        modelType: {
          validator: function (value) {
            return [ 'branch', 'home', 'room' ].includes(value)
          }
        }
      },
      computed: {
        modelOptions () {
          return this.modelType ? this[this.modelType + 'Options'] : []
        },
        propFiled () { // 保持@emit出去的value的数据结构与传入的value相同 除了msg_notify
          return this.value && Object.keys(this.value)
        },
        isDisabled () {
          return this.modelType && this.form.model === 'extend'
        },
        msgUsers () {
          return [ ...this.existUsers, ...this.users ]
        }
      },
      watch: {
        value (n) {
          const form = pick(this.form, this.propFiled)
          if (!isEqual(form, n)) {
            this.form = { ...this.form, ...n }
          }
        },
        form: {
          deep: true,
          handler (n) {
            // 选择同一配置 重置选项
            if (this.modelType && n.model === 'extend') {
              const data = pick(this.defaultConfig, this.propFiled)
              if (this.value.msg_notify) data.msg_notify = this.form.msg_notify
              this.$emit('input', data)
            } else {
              this.$emit('input', pick(n, this.propFiled))
            }
          }
        }
      },
      data () {
        return {
          visible: false,
          phoneError: '',
          newPhone: '',
          loading: false,
          branchOptions: [ { label: '公司统一配置', value: 'extend' }, { label: '门店独立配置', value: 'self' } ],
          homeOptions: [ { label: '门店统一配置', value: 'extend' }, { label: '房源独立配置', value: 'self' } ],
          roomOptions: [ { label: '房源统一配置', value: 'extend' }, { label: '房间独立配置', value: 'self' } ],
          options: [ 24, 48, 72, 120 ],
          lowPowerOptions: [ 10, 15, 20, 30 ],
          form: {
            model: '',
            enable_alarm: '',
            alarm_time: '',
            alarm_unlock: 10,
            msg_notify: []
            // low_power: ''
          },
          rules: {
            model: { required: !!this.modelType },
            enable_alarm: { required: true },
            alarm_time: { required: true },
            alarm_unlock: { required: true },
            msg_notify: { required: false },
            forbid_add_password: { required: true },
            forbid_add_tmp_password: { required: true }
            // low_power: { required: true }
          },
          users: []
        }
      },
      methods: {
        $validate () {
          return new Promise((resolve, reject) => {
            if (!this.$refs.form) reject(new Error(''))
            this.$refs.form.validate(valid => {
              valid ? resolve() : reject(new Error(''))
            })
          })
        },
        handleAddNotify () {
          if (this.form.msg_notify.includes(this.newPhone + '')) {
            this.phoneError = '该号码已添加'
          } else if (/^1\d{10}$/.test(this.newPhone + '')) {
            this.phoneError = ''
            this.form.msg_notify.push(this.newPhone + '')
            this.newPhone = ''
            this.visible = false
          } else {
            this.phoneError = '号码格式错误'
          }
        },
        handleDelNotify (index) {
          this.form.msg_notify.splice(index, 1)
        },
        handleFetchUsers: debounce(function (keyword) {
          this.fetchUsers(keyword)
        }, 300),
        async fetchUsers (keyword) {
          try {
            this.loading = true
            const res = await http.req(api.lock_msg_users, null, { offset: 0, limit: 10, keyword })
            const existUsers = this.existUsers.map(user => user.id)
            this.users = res.filter(data => !existUsers.includes(data.id))
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        }
      }
    }
</script>